// ==UserScript==
// @name     Baiduyun
// @version  3
// @grant    none
//@match   https://pan.baidu.com/*
// ==/UserScript==

function injectToContentScope(){
	
class LdkYun{
	constructor(){
		this.context = window.require('system-core:context/context.js').instanceForSystem;
		this.context.log.send = function(){}
	}

	showSelected(){
		this.context.list.getSelected();
	}

	downloadFileInfo(){
		let selected = this.context.list.getSelected();
		if(selected.length != 1){
			console.log('only can download one file at once');
			return null;
		}
		return selected[0];
	}

	showAria2Text(){
		let downloadInfo = this.downloadFileInfo();
		if(downloadInfo == null)
			return;
		let name = downloadInfo.server_filename;
		let dlink = `https://pcs.baidu.com/rest/2.0/pcs/file?method=download&app_id=250528&path=${encodeURIComponent(downloadInfo.path)}`;
		const headers = [
			"Cookie: $BAIDU_COOKIE",
			`User-Agent: ${navigator.userAgent}`];
		const headersStr = headers.map(item => `--header ${JSON.stringify(item)}`).join(' ');
		let aria2CmdLine = `aria2c --checksum=md5=${downloadInfo.md5} -c -s10 -k1M -x16 --enable-rpc=false -o ${JSON.stringify(name)} ${headersStr} ${JSON.stringify(dlink)}`
		console.log(aria2CmdLine);
	}
}
	console.log("ldkxingzhe's baiduyun injected");
	window.LdkYun = LdkYun;
	console.log("ldkxingzhe's baiduyun prepare compte");
}

function showDownloadLink(){
	if(!window.ldk){
		window.ldk = new LdkYun();
	}
	window.ldk.showAria2Text();
}

console.log("ldkxingzhe's baiduyun start injected");
var script = document.createElement('script');
script.appendChild(document.createTextNode(`(${injectToContentScope})();
${showDownloadLink}`));
(document.body || document.head || document.documentElement).appendChild(script);
